#!/bin/bash

################################################################################
# 精子银行管理系统 - 完整部署脚本
# Sperm Bank Management System - Full Deployment Script
#
# 功能：完整部署/更新整个系统（前端+后端）
#
# 使用方法：
#   chmod +x deploy.sh
#   ./deploy.sh
#
################################################################################

set -e  # 遇到错误立即退出

# ========== 颜色定义 ==========
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# ========== 配置 ==========
PROJECT_DIR="/var/www/sperm-bank_-db"
BACKEND_DIR="$PROJECT_DIR/backend-sperm-bank"
FRONTEND_DIR="$PROJECT_DIR/frontend"
BACKEND_SERVICE="sperm-bank-api"

# ========== 工具函数 ==========
print_header() {
    echo -e "\n${BLUE}========================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}========================================${NC}\n"
}

print_success() { echo -e "${GREEN}✓ $1${NC}"; }
print_error() { echo -e "${RED}✗ $1${NC}"; }
print_warning() { echo -e "${YELLOW}⚠ $1${NC}"; }

# ========== 开始部署 ==========
clear
echo -e "${GREEN}"
echo "╔════════════════════════════════════════════════════════╗"
echo "║     精子银行管理系统 - 完整部署                        ║"
echo "║     Sperm Bank Management System - Full Deployment     ║"
echo "╚════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# 1. 切换到项目目录
print_header "[1/6] 切换到项目目录"
cd "$PROJECT_DIR" || {
    print_error "无法切换到项目目录: $PROJECT_DIR"
    exit 1
}
print_success "当前目录: $(pwd)"

# 2. 更新代码
print_header "[2/6] 拉取最新代码"
if git pull origin master; then
    print_success "代码更新成功"
else
    print_error "代码更新失败"
    exit 1
fi

# 3. 重启后端
print_header "[3/6] 重启后端服务"

# 检查服务是否存在
if ! sudo systemctl list-units --all | grep -q "$BACKEND_SERVICE"; then
    print_error "后端服务 '$BACKEND_SERVICE' 不存在"
    echo ""
    echo "请检查："
    echo "  1. 服务名称是否正确？"
    echo "  2. 服务是否已创建？运行: sudo systemctl list-units | grep sperm"
    echo ""
    exit 1
fi

# 重启服务
if sudo systemctl restart "$BACKEND_SERVICE"; then
    print_success "后端服务已重启"
    sleep 2
    
    # 检查服务状态
    if sudo systemctl is-active --quiet "$BACKEND_SERVICE"; then
        print_success "后端服务运行正常"
    else
        print_error "后端服务启动失败"
        echo ""
        echo "查看详细错误信息："
        sudo systemctl status "$BACKEND_SERVICE" --no-pager
        echo ""
        echo "查看最近日志："
        sudo journalctl -u "$BACKEND_SERVICE" -n 20 --no-pager
        exit 1
    fi
else
    print_error "后端服务重启失败"
    echo ""
    echo "查看详细错误信息："
    sudo systemctl status "$BACKEND_SERVICE" --no-pager
    exit 1
fi

# 4. 安装前端依赖
print_header "[4/6] 安装前端依赖"
cd "$FRONTEND_DIR" || {
    print_error "无法切换到前端目录"
    exit 1
}
if npm install; then
    print_success "前端依赖安装成功"
else
    print_warning "前端依赖安装失败，继续构建..."
fi

# 5. 构建前端
print_header "[5/6] 构建前端"
if npm run build; then
    print_success "前端构建成功"
else
    print_error "前端构建失败"
    exit 1
fi

# 6. 验证部署
print_header "[6/6] 验证部署"
print_success "前端构建文件: $FRONTEND_DIR/dist"
print_success "后端服务状态:"
sudo systemctl status "$BACKEND_SERVICE" --no-pager | head -5

# 完成
echo -e "\n${GREEN}╔════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║              ✓ 部署完成！                              ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════════════╝${NC}\n"

echo -e "${YELLOW}注意事项：${NC}"
echo "  1. 请在浏览器中按 Ctrl+Shift+Delete 清除缓存"
echo "  2. 或按 F12 -> Network -> Disable cache"
echo "  3. 刷新页面 (F5 或 Ctrl+R)"
echo ""

